# -*- coding: utf8 -*-

__author__ = "Sergey Dryabzhinsky"

__doc__ = """
Обработка изображения

@author: Sergey Dryabzhinsky
"""

import math
from Image import BICUBIC, FLIP_LEFT_RIGHT

def process_image( im, mirror = False, parts = 100 ):
    """
    Process image data and calculate some results

    @return:    calculated data:
                {
                    "color" : bool,
                    "mean_gray" : int,
                    "vector" : list
                }
    @rtype:     dict
    """

    result = {
        "color" : False,
        "mean_gray" : 0,
        "vector" : None
    }

    if mirror:
        im = im.transpose( FLIP_LEFT_RIGHT )

    w, h = im.size

    vector = range(parts)
    vector = map(lambda item: None, vector)
    
    vw = math.sqrt(float(w)/float(h)*parts)
    vh = math.sqrt(float(h)/float(w)*parts)

    # resample for bicubic
    rsw = int( math.ceil(vw) ) * 4
    rsh = int( math.ceil(vh) ) * 4

    im = im.resize( (rsw, rsh), BICUBIC )

    w, h = im.size

    wr = range( w )
    hr = range( h )

    meanColor = 0    
    
    if im.mode == "P":
        pal = im.getpalette()

    for x in wr:
        for y in hr:
            r = g = b = mc = 0
            if im.mode == "RGBA":
                r, g, b, a = im.getpixel( ( x, y ) )
                mc = math.sqrt(r * r * 0.241 + g * g * 0.691 + b * b * 0.068)
            if im.mode == "RGB":
                r, g, b = im.getpixel( ( x, y ) )
                mc = math.sqrt(r * r * 0.241 + g * g * 0.691 + b * b * 0.068)
            elif im.mode == "P":
                ind = im.getpixel( ( x, y ) )
                r, g, b = pal[ind * 3:ind * 3 + 3]
                mc = math.sqrt(r * r * 0.241 + g * g * 0.691 + b * b * 0.068)
            elif im.mode == "L":
                mc = r = g = b = im.getpixel( ( x, y ) )
                
            if r != g or g != b:
                result["color"] = True

            vn = int( float(x*h + y)/float(w*h)*(vw*vh) )

            if vector[ vn ] is None:
                vector[ vn ] = { "c" : 0, "n" : 0 }
            vector[ vn ][ "c" ] += mc
            vector[ vn ][ "n" ] += 1
            
            meanColor += mc

    meanColor /= w*h
    result["mean_gray"] = meanColor

    for key in xrange(parts):
        item = vector[key]
        vector[key] = int(item["c"] * 1.0 / item["n"])

    result["vector"] = vector
    return result


def compare_vectors( v1, v2, min_diff, correction=0, parts=100):
    n_ineq = 0
    for key in xrange(parts):
        p1 = v1[key]
        p2 = v2[key]
        if abs(p1-p2+correction)/float(p1) <= min_diff:
            n_ineq += 1

    return n_ineq

def diff_vectors( v1, v2, correction=0, parts = 100):
    diff = range(parts)
    for key in xrange(parts):
        p1 = v1[key]
        p2 = v2[key]
        diff[key] = abs(p1-p2+correction)/float(p1)

    return diff
